from os.path import join
import sys
import os
import re

def key_func(filename):
    match = pattern.match(filename)
    if match:
        return int(match.group(1))
    else:
        return 0

video_dir = sys.argv[1] 
out_name = os.path.basename(video_dir)
ts_files = [f for f in os.listdir(video_dir) if f.endswith('.ts')]
pattern = re.compile(r'(\d+)\.ts') 

ts_files = [f for f in os.listdir(video_dir) if f.endswith('.ts')] 
ts_files.sort(key=key_func)
output_path = os.path.join(video_dir, f'{out_name}.ts') 

with open(output_path, 'wb') as output:
    for ts_file in ts_files:
        input_path = join(video_dir, ts_file)
        with open(input_path, 'rb') as input:
            output.write(input.read())

print(f'TS files merged to {output_path}')
